import { Component, OnInit } from '@angular/core';
import { NavController, PickerController, AlertController } from '@ionic/angular';
import { HttpService } from 'src/app/service/http.service';
import { UrlService } from 'src/app/service/url.service';
import { ToolService } from 'src/app/service/tool.service';
import { ConfigService } from 'src/app/service/config.service';
import { PopwinService } from 'src/app/service/popwin.service';
import { Storage } from '@ionic/storage';

@Component({
  selector: 'app-quota',
  templateUrl: './quota.page.html',
  styleUrls: ['./quota.page.scss'],
})
export class QuotaPage implements OnInit {

  public balance="0.00";//万漉会的余额
  public lockMoney="0.00";//冻结的余额
  public listInfo=[];//不同游戏名称对应的余额值
  public gameName=[];//获取游戏的名称
  public isShowBtnGroup=false;
  public totalBalance="0.00";
  public firstName="万漉国际";
  public firstID="0";
  public firstBalance="0.00";
  public secondName="请选择";
  public secondID="0";
  public secondBalance="0.00";
  public isTrans=true;//是否立即转账
  public isTransAll=true;//是否一键回收
  
  public inputVal="";//表单中输入的值

  constructor(private navCtrl:NavController,private http:HttpService,private popWin:PopwinService,private pickercontroller:PickerController,private alertController:AlertController,private store:Storage) { }

  ngOnInit() {
    if(!ConfigService.is3rd){//没有第三方直接放回
      this.backClick();
      return;
    }
    let that=this;
    this.store.get(ConfigService.ROLE_KEY).then((data) => {
      if (data == '2') {
        that.popWin.toast("试玩账号不能进入");
        that.backClick();
        return;
      }
      this.getBlanceMoney();
      this.getSelectOption();
    });
   
  }

  backClick(){
    this.navCtrl.navigateBack("/tabs/recharge");
  }
  /**
   * 重新刷新
   */
  onRefresh(){
      this.inputVal="";
      this.getBlanceMoney(true);
  }
  /**
   * 获取余额的数据
   */
  getBlanceMoney(isTip=false){
    let that=this;
    this.http.get(UrlService.THIRD_SHOWTRANS, { "callback": "JSONP_CALLBACK" }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let res = ToolService.aesDecodeToJson(data.data);
        console.log("获取的余额数据--",res);
        that.balance=res.balance;
        that.firstBalance=res.balance;
        that.secondBalance='0.00';
        that.lockMoney=res.lock_money;
        that.listInfo=res.info;
        that.firstName="万漉国际";
        that.secondName="请选择";
        that.calcTotalBalance(res.info);
        if(isTip){
            that.popWin.toast("刷新余额成功");
        }
        if(!ToolService.isEmpty(res.error)){   //有其它异常就报出来
          that.popWin.toast(res.error);
        }
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }

  calcTotalBalance(balanceList){
    let res="0";
    for(let item in balanceList){
      res=(parseFloat(res)+parseFloat(balanceList[item]['balance'])).toFixed(2);
    }
    this.totalBalance=res;
  }
  /**
   * 获取游戏平台的名称
   */
  getSelectOption(){
    let that=this;
    this.http.get(UrlService.THIRD_GETPLATFORMNAMES, { "callback": "JSONP_CALLBACK" }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let res = ToolService.aesDecodeToJson(data.data);
        if(!ToolService.isEmpty(res) && res.length>=1){
            that.isShowBtnGroup=true;
            res.push({"id": "0","platform_name": "万漉国际"});
            that.gameName=res;
        }
        console.log("拼接后获取游戏平台的名称--",that.gameName);
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }
  /**
   * 立即转账
   */
  onTrans(){
    if((this.firstID=="0" && this.secondID=="0") || (this.firstID==this.secondID)){
        this.popWin.toast("请选择两个不同的平台");
        return;
    }
    if(!ToolService.isNumber(this.inputVal) || ToolService.isEmpty(this.inputVal) || (this.inputVal=="0")){
      this.popWin.toast("需输整数");
      return;
    }
    if(this.firstID!=='0' && this.secondID!=='0'){
      this.popWin.toast("必须其中一个选中万漉国际");
      return;
    }
    if(parseInt(this.inputVal)>this.getMaxUserBalance()){
      this.popWin.toast("目标账户余额不足");
      return;
    }
    if(!this.isTrans){
      this.popWin.toast("操作太频繁,请稍后再次尝试");
      return;
    }
    this.isTrans=false;
    let that=this;
    let obj = "{\"fromPlatformId\":\"" + this.firstID + "\",\"toPlatformId\":\"" + this.secondID + "\",\"money\":\"" + parseInt(this.inputVal) + "\"}";
    this.http.get(UrlService.THIRD_GAMETRANS, { "callback": "JSONP_CALLBACK", "data": ToolService.aesEncode(obj) }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      that.isTrans=true;
      if (data.code == ConfigService.SUCCESS_CODE) {
        let res = ToolService.aesDecodeToJson(data.data);
        that.presentAlert("已转账"+parseInt(this.inputVal)+"元成功");
        console.log("转帐的数据返回的结果--",res);
        that.inputVal="";
        that.getBlanceMoney();
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast("转帐失败");
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
      that.isTrans=true;
    });
  }

  getMaxUserBalance(){
    let tempMoney=0;
    for(let item in this.listInfo){
      if(""+this.firstID==this.listInfo[item]['platform_id']+""){
        tempMoney=parseInt(this.listInfo[item]['balance']);
        break;
      }
    }
    return tempMoney;
  }

  getPlatformBalance(platformId){
    let tempMoney=0;
    for(let item in this.listInfo){
      if(""+platformId==this.listInfo[item]['platform_id']+""){
        tempMoney=this.listInfo[item]['balance'];
        break;
      }
    }
    return tempMoney;
  }
  /**
   * 一键回收
   */
  onRecycle(){
    let that=this;
     this.presentAlertConfirm("是否一键回收?","所有其它平台一起转账到万漉国际",function(){
        if(that.isTransAll){
          that.isTransAll=false; 
          that.recycleNet();
        }
        
     });
  }
  recycleNet(){
    let that=this;
    this.http.get(UrlService.THIRD_ALLTRANS, { "callback": "JSONP_CALLBACK"}).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      that.isTransAll=true; 
      if (data.code == ConfigService.SUCCESS_CODE) {
        let res = ToolService.aesDecodeToJson(data.data);
        console.log("其它平台转账到万漉国际上面--",res);
        that.presentAlert("转账到万漉国际共"+res.allCount+"元");
        that.inputVal="";
        that.getBlanceMoney();
        if(!ToolService.isEmpty(res.error)){   //有其它异常就报出来
          that.popWin.toast(res.error);
        }
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast("转帐失败");
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
      that.isTransAll=true; 
    });
  }

  /**
   * 最大的可转额
   */
  onInputMax(){
      this.inputVal=this.getMaxUserBalance()+"";
  }

  async presentAlertConfirm(header,message,callback) {
    const alert = await this.alertController.create({
      header:header,
      message: message,
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          handler: (blah) => {}
        }, {
          text: '确定',
          handler: () => {
            callback();
          }
        }
      ]
    });
    await alert.present();
  }

  async presentAlert(msg) {
    const alert = await this.alertController.create({
      header: '转账成功',
      message: msg,
      buttons: ['确定']
    });
    await alert.present();
  }

  /**
   * picker选择器
   * @param type 类型是第一个选项还是第二个选择
   * @param numColumns 默认是1列
   */

  async  openPicker(type,numColumns = 1) {
    let that=this;
    let data= this.gameName;
    if(data.length<=1){
      return;
    }
   let numOptions=data.length;
   let multiColumnOptions=[];
   let arr=[];
    for(let tempItem in data){
      arr.push(data[tempItem].platform_name);
    }
    multiColumnOptions.push(arr);
    const picker = await this.pickercontroller.create({
      columns: this.getColumns(numColumns, numOptions, multiColumnOptions),
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '确认',
          handler: (value) => {
            if(type=="one"){
                that.firstName=value['col-0'].text;
                that.firstID=data[value['col-0'].value].id+"";
                that.firstBalance=that.getPlatformBalance(that.firstID)+"";
            }else if(type=="two"){
              that.secondName=value['col-0'].text;
              that.secondID=data[value['col-0'].value].id+"";
              that.secondBalance=that.getPlatformBalance(that.secondID)+"";
            }
          }
        }
      ]
    });
    await picker.present();
  }

  getColumns(numColumns, numOptions, columnOptions) {
    let columns = [];
    for (let i = 0; i < numColumns; i++) {
      columns.push({
        name: `col-${i}`,
        options: this.getColumnOptions(i, numOptions, columnOptions)
      });
    }
    return columns;
  }

  getColumnOptions(columnIndex, numOptions, columnOptions) {
    let options = [];
    for (let i = 0; i < numOptions; i++) {
      options.push({
        text: columnOptions[columnIndex][i % numOptions],
        value: i
      })
    }
    return options;
  }

  /**
   * 跳转到账号充值的页面
   */
  toAccountrecharge(){
    this.navCtrl.navigateForward("/accountrecharge");
  }



}
